package org.algorithm.biubiu.wheel_1.链表;

import org.algorithm.biubiu.wheel_1.common.ListNode;

import java.util.HashSet;

/**
 * @author jiazhaoxin
 * @Date 2022/2/14
 * @Desc {https://leetcode-cn.com/problems/linked-list-cycle/submissions/}
 */
public class 环形链表 {



    public boolean hasCycle(ListNode head) {
        HashSet<ListNode> set = new HashSet<>();
        boolean result = false;
        ListNode dummy = head;
        while (dummy != null) {
            ListNode next = dummy.next;
            if (set.contains(next)) {
                result = true;
                break;
            } else {
                set.add(next);
            }
            dummy = next;
        }
        return result;
    }


    public boolean hasCycle2(ListNode head) {
         if(head==null){
             return false;
         }
         ListNode slow = head;
         ListNode fast = head.next;

         while (slow!=fast){
             if(fast==null ||fast.next==null){
                 return  false;
             }
             slow = slow.next;
             fast = fast.next.next;
         }
         return  true;
    }
}
